package cumeo89.chii.client.entry.renderer;

import static cumeo89.chii.client.entry.Constants.*;

import com.google.gwt.xml.client.Attr;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;

import cumeo89.chii.client.entry.AbstractRenderer;
import cumeo89.chii.client.entry.Renderer;
import cumeo89.chii.client.ui.ExtendedPanel;
import cumeo89.chii.client.ui.HeaderPanel;
import cumeo89.chii.client.ui.TrivialPanel;
import cumeo89.chii.client.util.MyArrays;

class HeaderListRenderer extends AbstractRenderer {

	static final String[] SUPPORTED_CODES = { E_LANG, E_POS, "wlist", "expr",
			"pron", "etym", "translit", "ref", "usage", "forms", "trans" };

	static final String[] SUPPORTED_NAMES = { "-", "-", "-", "Thành ngữ",
			"Cách phát âm", "Từ nguyên", "Cách chuyển tự", "Tham khảo",
			"Cách dùng", "Dạng động từ", "Dịch" };

	private HeaderPanel panel = new HeaderPanel();
	private TrivialPanel container = new TrivialPanel("div");

	public HeaderListRenderer() {
		panel.setContentWidget(container);
		// set style name later
		initWidget(panel);
	}

	@Override
	public void prepareWidget(Node node, boolean selected) {
		super.prepareWidget(node, selected);
		String name = MyArrays.translate(((Element) node).getTagName(),
				SUPPORTED_CODES, SUPPORTED_NAMES);
		if (!"-".equals(name)) {
			panel.setTitleWidget(new TrivialPanel("span",
					name == null ? "&lt;không rõ&gt;" : name));
		}
		if (selected) {
			panel.setExpanded(true);
		}
	}

	@Override
	public void addRenderer(Renderer child) {
		Node node = child.getRenderedNode();
		if (node.getNodeType() == Node.ATTRIBUTE_NODE
				&& "code".equals(((Attr) node).getName())) {
			panel.setTitleWidget(child.getWidget());
		}
		super.addRenderer(child);
	}

	@Override
	public void removeRenderer(Renderer child) {
		Node node = child.getRenderedNode();
		if (node.getNodeType() == Node.ATTRIBUTE_NODE
				&& "code".equals(((Attr) node).getName())) {
			panel.setTitleWidget(null);
		}
		super.removeRenderer(child);
	}
	
	@Override
	public void notifyChildSelected() {
		super.notifyChildSelected();
		panel.setExpanded(true);
	}

	@Override
	protected ExtendedPanel getChildContainer() {
		return container;
	}
}